<?php

namespace App\Repositories;

use App\Models\User;
use Illuminate\Database\Eloquent\Collection;

class UserRepository extends BaseRepository
{
    public function __construct(User $model)
    {
        parent::__construct($model);
    }

    /**
     * 根据openid查找用户
     */
    public function findByOpenid(string $openid): ?User
    {
        return $this->model->where('openid', $openid)->first();
    }

    /**
     * 根据unionid查找用户
     */
    public function findByUnionid(string $unionid): ?User
    {
        return $this->model->where('unionid', $unionid)->first();
    }

    /**
     * 根据手机号查找用户
     */
    public function findByPhone(string $phone): ?User
    {
        return $this->model->where('phone', $phone)->first();
    }

    /**
     * 创建或更新用户
     */
    public function createOrUpdateByOpenid(string $openid, array $data): User
    {
        return $this->model->updateOrCreate(
            ['openid' => $openid],
            array_merge($data, ['last_login_at' => now()])
        );
    }

    /**
     * 更新最后登录时间
     */
    public function updateLastLogin(int $userId): bool
    {
        return $this->update($userId, ['last_login_at' => now()]);
    }

    /**
     * 获取活跃用户
     */
    public function getActiveUsers(): Collection
    {
        return $this->model->where('is_active', true)->get();
    }

    /**
     * 根据昵称搜索用户
     */
    public function searchByNickname(string $nickname): Collection
    {
        return $this->model->where('nickname', 'like', "%{$nickname}%")->get();
    }
}
